<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 订单列表
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <span class="search-title">订单号：</span>
                <el-input v-model="query.param.orderNumber" placeholder="订单号" class="handle-input mr10"
                          style="width: 200px"></el-input>
                <span class="search-title">推荐ID:</span>
                <el-input v-model="query.param.recommendUserId" placeholder="推荐ID" type="number" class="handle-input mr10"
                          style="width: 100px"></el-input>
                <span class="search-title">支付类型：</span>
                <el-select v-model="query.param.payType" placeholder="支付类型" class="handle-select mr10">
                    <el-option key="3" label="请选择" value=""></el-option>
                    <el-option key="0" label="未支付" value="0"></el-option>
                    <el-option key="1" label="支付宝" value="1"></el-option>
                    <el-option key="2" label="微信" value="2"></el-option>
                </el-select>
                <span class="search-title">订单状态：</span>
                <el-select v-model="query.param.orderStatus" placeholder="订单状态" multiple>
                    <el-option
                            v-for="item in order_status_options"
                            :key="item.value"
                            :label="item.text"
                            :value="item.value">
                    </el-option>
                </el-select>
                &nbsp;
                <span class="search-title">退款状态：</span>
                <!--子状态 7-退货申请 8-退货货物快递中 9-退货成功 10-退货失败-->
                <el-select v-model="query.param.orderSubStatus" placeholder="退款状态" multiple>
                    <el-option
                            v-for="item in refund_status_options"
                            :key="item.value"
                            :label="item.text"
                            :value="item.value">
                    </el-option>
                </el-select>
                &nbsp;&nbsp;
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-search" @click="downExcel">导出到EXCEL</el-button>
                <br>
                <span class="search-title">联系人：</span>
                <el-input v-model="query.param.receivingName" placeholder="联系人" class="handle-input mr10"
                          style="width: 120px"></el-input>
                <span class="search-title">创建时间：</span>
                <el-date-picker
                        v-model="query.param.createStartTime"
                        :picker-options="projectStartDate"
                        type="date"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        style="width: 130px;"
                        placeholder="开始日期"
                ></el-date-picker>
                -
                <el-date-picker
                        v-model="query.param.createEndTime"
                        :picker-options="projectEndDate"
                        type="date"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        style="width: 130px;"
                        placeholder="结束日期"
                ></el-date-picker>
            </div>
            <el-table
                    :data="orderList"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
                    @cell-dblclick="shuangjiCopy">
                <el-table-column type="selection" width="60" align="center" prop="id"></el-table-column>
                <!--                <el-table-column prop="id"  width="55" align="center"  style="display:none"></el-table-column>-->
                <!--                <el-table-column label="用户ID" width="120">-->
                <!--                    <template slot-scope="scope">{{scope.row.user.userId}}|{{scope.row.user.nickName}}</template>-->
                <!--                </el-table-column>-->
                <!--                <el-table-column label="分销商ID" width="200">-->
                <!--                    <template slot-scope="scope" v-if="scope.row.distributor">{{scope.row.distributor.id}}|{{scope.row.distributor.userName}}</template>-->
                <!--                </el-table-column>-->
                <el-table-column prop="orderNumber" label="订单号" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="支付类型" width="100">
                    <template slot-scope="scope">
                        {{scope.row.payType == 0 ? '' : ''}}
                        {{scope.row.payType == 1 ? '支付宝' : ''}}
                        {{scope.row.payType == 2 ? '微信' : ''}}
                        {{scope.row.payType == 3 ? '余额' : ''}}
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="下单日期" width="180"></el-table-column>
                <el-table-column prop="payTime" label="支付日期" width="180"></el-table-column>
                <el-table-column label="订单金额" width="150">
                    <template slot-scope="scope">￥{{scope.row.actualPrice}}</template>
                </el-table-column>
                <el-table-column prop="receivingName" label="联系人" width="90"></el-table-column>
                <el-table-column label="订单状态" width="160">
                    <template slot-scope="scope">
                        <span style="color: #00a854">{{scope.row.orderStatusValue}}</span>
                        <span v-if="scope.row.refundStatusValue != null" style="color: red">->{{scope.row.refundStatusValue}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-lx-attentionfill"
                                @click="handleOrderDetail(scope.$index, scope.row)"
                        >订单详情
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-lx-forwardfill"
                                v-if="scope.row.orderStatus == 2"
                                @click="handleEditFaHuo(scope.$index, scope.row)"
                        >点击发货
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-lx-forwardfill"
                                v-if="scope.row.refundStatus == 7"
                                @click="handleEditRefundApply(scope.row)"
                        >审核退货申请
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-lx-forwardfill"
                                v-if="scope.row.refundStatus == 8"
                                @click="handleEditRefundPrice(scope.row)"
                        >确认退款
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total,sizes, prev, pager, next"
                        :current-page="query.pageNum"
                        :page-sizes="[10,20,50,100]"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="发货" :visible.sync="editVisible" width="30%" v-if="address != null">
            <div class="handle-box">
                <label class="title-lable">收货人:&nbsp;{{address.receivingName}}&nbsp;&nbsp;&nbsp;{{address.phone}}</label>
                <br>
                <label class="title-lable">地 址:&nbsp;
                    {{address.provinceName}}{{address.cityName}}{{address.areaName}}{{address.street}}
                </label>
                <br>
                <label class="title-lable">当前状态:&nbsp;&nbsp;&nbsp;<span style="color: red">已支付</span></label>
                <br>
                <label class="title-lable">购买数量:&nbsp;
                    {{fahuoForm.number}}
                </label>
            </div>
            <div>
                选择快递：
                <el-input type="textarea" rows="1" v-model="fahuoForm.expressCompany"></el-input>
                输入快递号：
                <el-input type="textarea" rows="1" v-model="fahuoForm.expressNumber"></el-input>
                <!-- 卡号(enter换行)：<el-input type="textarea" rows="3" v-model="cardNumber"></el-input> -->
            </div>
            <el-form ref="form" :model="fahuoForm" label-width="70px">
                发货备注:
                <el-input type="textarea" rows="5" v-model="fahuoForm.remark"></el-input>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确定发货</el-button>
            </span>
        </el-dialog>

        <!-- 详情弹框 -->
        <order-detail v-if="isOrderDetail" ref="orderDetails"></order-detail>
    </div>
</template>

<script>
    import OrderDetail from './orderDetail';

    export default {
        name: 'orderList',
        components: {
            OrderDetail
        },
        data() {
            return {
                query: {
                    pageNum: 1,
                    pageSize: 10,
                    param: {
                        orderStatus: [],//订单状态1-未支付 2-已支付 3-已发货 4-已收货 5-未支付取消订单  7-退货申请 8-退货货物快递中 9-退货成功 10-退货失败
                        refundStatus: [],//退款状态 7-退货申请 8-退货货物快递中 9-退货成功 10-退货失败
                        nickName: '',//用户名称 根据用户名查询
                        orderNumber: '',//订单号
                        createStartTime: '',
                        createEndTime: '',
                        receivingName: '',//联系人
                        recommendUserId: '',
                        payType: ''//分销商id查询
                    }
                },
                orderList: [],
                multipleSelection: [],
                delList: [],
                editVisible: false,
                pageTotal: 0,
                fahuoForm: {
                    id: '',
                    remark: '',
                    expressCompany: '',
                    expressNumber: '',
                    cardNumber: [],
                    number: ''
                },
                cardNumber: '',
                number: '',
                address: {},
                idx: -1,
                id: -1,
                isOrderDetail: false,
                projectStartDate: this.beginDate(),
                projectEndDate: this.processDate(),
                order_status_options: [{
                    value: 2,
                    text: '已支付'
                }, {
                    value: 1,
                    text: '待支付'
                }, {
                    value: 3,
                    text: '已发货'
                }, {
                    value: 4,
                    text: '已收货'
                }, {
                    value: 5,
                    text: '已取消'
                }],
                refund_status_options: [{
                    value: 7,
                    text: '已申请退货'
                }, {
                    value: 8,
                    text: '退货快递中'
                }, {
                    value: 9,
                    text: '退货成功'
                }, {
                    value: 10,
                    text: '退货失败'
                }]
            };
        },
        created() {
            this.getData();
        },
        methods: {
            // 获取 easy-mock 的模拟数据
            getData() {
                orderList(this.query).then(res => {
                    if (res.returnCode == 200) {
                        this.orderList = res.data.list;
                        this.pageTotal = res.data.total;
                    } else {
                        this.orderList = null;
                        this.pageTotal = 0;
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageNum', 1);
                this.getData();
            },
            //导出到excel
            downExcel(){
                exportExcel(this.query.param);
            },
            // 跳转详情
            handleOrderDetail(index, row) {
                this.isOrderDetail = true;
                this.$nextTick(() => {
                    this.$refs.orderDetails.getOrderDetail(row.id);
                });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 发货操作
            handleEditFaHuo(index, row) {
                this.idx = index;
                this.fahuoForm = {
                    id: row.id,
                    remark: row.remark,
                    number: row.number
                };
                this.address = row.address;
                this.editVisible = true;
            },
            // 保存编辑
            saveEdit() {
                // if(this.fahuoForm.expressCompany == null){
                //     this.$message.success(`请输入快递公司！！！`);
                //     return;
                // }
                // if(this.fahuoForm.expressNumber == null){
                //     this.$message.success(`请输入快递单号！！！`);
                //     return;
                // }
                // if(this.cardNumber == ''){
                //     this.$message.success(`请输入正确的卡号！！！`);
                //     return;
                // }
                this.fahuoForm.cardNumber = this.cardNumber.split('\n');
                orderDelivered(this.fahuoForm).then(res => {
                    if (res.returnCode == 200) {
                        this.editVisible = false;
                        this.$message.success(`发货成功！！！`);
                        this.$set(this.query);
                        this.getData();
                    } else {

                        this.$message.success(res.returnMsg);
                    }
                });
            },
            //审核退货申请弹出框
            handleEditRefundApply(row) {
                const h = this.$createElement;
                this.$msgbox({
                    title: '审核退货申请',
                    message: h('p', null, [
                        h('span', null, '当前订单状态:'),
                        h('i', { style: 'color: red' }, row.orderStatusValue + '->' + row.refundStatusValue),
                        h('br', null, ''),
                        h('span', null, '申请退货说明:'),
                        h('i', { style: 'color: blue' }, row.refundOrder.remark)
                    ]),
                    showCancelButton: true,
                    distinguishCancelAndClose: true,
                    confirmButtonText: row.orderStatus == 2 ? '确认退款' : '审核通过',
                    cancelButtonText: '驳回申请',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            done();
                            var data = row.refundOrder;
                            updateApplySuccessRefund(data).then(res => {
                                if (res.returnCode == 200) {
                                    this.$message.success(res.returnMsg);
                                    this.$set(this.query);
                                    this.getData();
                                } else {
                                    this.$message.success(res.returnMsg);
                                }
                            });
                        }
                        if (action === 'cancel') {
                            done();
                            this.applyFail(row, '');
                        }
                        if (action === 'close') {
                            done();
                        }
                    }
                }).catch(() => {
                });
            },
            //审核失败
            applyFail(row, error) {
                //输入失败原因
                var failRemark = prompt('请输入驳回申请原因' + error);
                if (failRemark == null) {
                    alert('取消本次审核!!!!!!');
                    return;
                }
                if (failRemark.length < 5) {
                    this.applyFail(row, '(不能为空或者小于五个字)');
                    return;
                }
                var data = row.refundOrder;
                data.failRemark = failRemark;
                updateApplyFailRefund(data).then(res => {
                    if (res.returnCode == 200) {
                        this.$message.success(`审核退款单驳回成功！！！`);
                        this.$set(this.query);
                        this.getData();
                    } else {
                        this.$message.success(res.returnMsg);
                    }
                });
            },
            // 收到退货快递过后执行退款
            handleEditRefundPrice(row) {
                if (confirm('是否确认退款到用户支付账户？？？')) {
                    var data = row.refundOrder;
                    refundUserPrice(data).then(res => {
                        if (res.returnCode == 200) {
                            this.$message.success(`已经退款到用户支付账户！！！`);
                            this.$set(this.query);
                            this.getData();
                        } else {
                            this.$message.success(res.returnMsg);
                        }
                    });
                }
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageNum', val);
                this.getData();
            },
            handleSizeChange(val) {
                this.$set(this.query, 'pageSize', val);
                this.getData();
            },
            // 日期选择约束
            beginDate() {
                const self = this;
                return {
                    disabledDate(time) {
                        if (self.query.param.createEndTime) {
                            //如果结束时间不为空，则小于结束时间
                            return (
                                new Date(self.query.param.createEndTime).getTime() < time.getTime()
                            );
                        } else {
                            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
                        }
                    }
                };
            },
            processDate() {
                const self = this;
                return {
                    disabledDate(time) {
                        if (self.query.param.createStartTime) {
                            //如果开始时间不为空，则结束时间大于开始时间
                            return (
                                new Date(self.query.param.createStartTime).getTime() > time.getTime()
                            );
                        } else {
                            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
                        }
                    }
                };
            }, shuangjiCopy(row, column) {
                this.$copyText(row[column.property]).then(
                    res => {

                    },
                    err => {

                    }
                );
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .mr10 {
        margin-right: 10px;
        padding: 5px 0px;
    }

    .search-title {
        font-size: 14px;
    }

    .title-lable {
        font-size: 14px;
    }

</style>